package com.rt.easyjava.base.biz1.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rt.easyjava.base.biz1.bean.TmptTableBiz;
import com.rt.easyjava.base.biz1.bean.TmptUserSetting;
import com.rt.easyjava.base.biz1.controller.base.TmptTableController;
import com.rt.easyjava.base.biz1.dto.TmptTableBizDto;
import com.rt.easyjava.base.biz1.dto.ZipTmptTableDto;
import com.rt.easyjava.base.biz1.mapper.TmptUserSettingMapper;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.utils.others.StringUtils;
import com.rt.easyjava.common.utils.others.SwitchLineCamel;
import com.rt.easyjava.common.utils.zip.ZipUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * 前端控制器
 * 1，自定义代码：源码生成器，创建模板，第一次生成源码时，会自动创建此类，之后生成源码时，此类将不做修改处理；
 *    所以，程序员应该在这个类里写自己的代码，后续需求变更，自动生成源码时，不影响此类。
 * 2，用户信息可直接形参获取：String (_userId，_loginName，_userName，_companyId，_userJson)
 * @author wuxiaoyong
 * @since 2020-07-04
 * 用户信息可直接形参获取：String (_userId，_loginName，_userName，_companyId，_userJson)
 */
@Slf4j
@Api(tags = "TmptTableBizController -  控制类")
@RequestMapping("/coding/tmptTable")
@Controller
public class TmptTableBizController extends TmptTableController {

    @Resource
    private TmptUserSettingMapper tmptUserSettingMapper;

    @PreAuthorize("hasAuthority('tmpt:query')")
    @ApiOperation("分页查询列表（适合单表查询）")
    @GetMapping(value = "/zipSourceFiles")
    @ResponseBody
    public Result zipSourceFiles(@ModelAttribute ZipTmptTableDto zipTmptTableDto, String _userId, HttpServletResponse response) throws IOException {

        String javaProjPath = "";
        String viewProjPath = "";
        String moduleName = zipTmptTableDto.getModuleName();
        String tableName = zipTmptTableDto.getTableName();
        String projectNameJava = zipTmptTableDto.getProjectNameJava();
        String projectNameView = zipTmptTableDto.getProjectNameView();

        // 数据库中取源码路径
        TmptUserSetting tmptUserSettingParam = new TmptUserSetting();
        tmptUserSettingParam.setCreatemanId(Long.parseLong(_userId));
        tmptUserSettingParam.setDeleteflag(0);
        QueryWrapper queryWrapper = new QueryWrapper(tmptUserSettingParam);
        List<TmptUserSetting> tmptUserSettingList = tmptUserSettingMapper.selectList(queryWrapper);
        for (TmptUserSetting tmptUserSetting : tmptUserSettingList) {
            String name = tmptUserSetting.getName();
            String value = tmptUserSetting.getValue();
            if ("mybatis-plus.generator.path".equalsIgnoreCase(name)) {
                javaProjPath = value;
                continue;
            }
            if ("mybatis-plus.generator.vue.path".equalsIgnoreCase(name)) {
                viewProjPath = value;
                continue;
            }
            if (StringUtils.isNull(moduleName)) {
                if ("mybatis-plus.generator.module".equalsIgnoreCase(name)) {
                    moduleName = value;
                    continue;
                }
            }
        }

        // path
        String mainPath = javaProjPath+File.separator+moduleName+File.separator+"src"+File.separator+"main";
        String packagePath = "com"+File.separator+"rt"+File.separator+"easyjava"+File.separator+moduleName;
        String className = SwitchLineCamel.switch2Property(tableName).substring(0,1).toUpperCase()+SwitchLineCamel.switch2Property(tableName).substring(1);
        String classNameFirstWordLower = SwitchLineCamel.switch2Property(tableName).substring(0,1).toLowerCase()+SwitchLineCamel.switch2Property(tableName).substring(1);
        // path for zip
        String mainPath4zip = "easyjava"+File.separator+projectNameJava+File.separator+moduleName+File.separator+"src"+File.separator+"main";
        // zip文件
        //bean
        String beanPath = mainPath+File.separator+"java"+File.separator+packagePath+File.separator+"bean";
        String beanPath4zip = mainPath4zip+File.separator+"java"+File.separator+packagePath+File.separator+"bean";
        File beanFile = new File(beanPath+File.separator+className+"Biz.java");
        File beanBaseFile = new File(beanPath+File.separator+"base"+File.separator+className+".java");
        //dto
        String dtoPath = mainPath+File.separator+"java"+File.separator+packagePath+File.separator+"dto";
        String dtoPath4zip = mainPath4zip+File.separator+"java"+File.separator+packagePath+File.separator+"dto";
        File dtoFile = new File(dtoPath+File.separator+className+"BizDto.java");
        File dtoBaseFile = new File(dtoPath+File.separator+"base"+File.separator+className+"Dto.java");
        //mapper
        String mapperPath = mainPath+File.separator+"java"+File.separator+packagePath+File.separator+"mapper";
        String mapperPath4zip = mainPath4zip+File.separator+"java"+File.separator+packagePath+File.separator+"mapper";
        File mapperFile = new File(mapperPath+File.separator+className+"BizMapper.java");
        File mapperBaseFile = new File(mapperPath+File.separator+"base"+File.separator+className+"Mapper.java");
        //controller
        String controllerPath = mainPath+File.separator+"java"+File.separator+packagePath+File.separator+"controller";
        String controllerPath4zip = mainPath4zip+File.separator+"java"+File.separator+packagePath+File.separator+"controller";
        File controllerFile = new File(controllerPath+File.separator+className+"BizController.java");
        File controllerBaseFile = new File(controllerPath+File.separator+"base"+File.separator+className+"Controller.java");
        //service.impl
        String serviceImplPath = mainPath+File.separator+"java"+File.separator+packagePath+File.separator+"service"+File.separator+"impl";
        String serviceImplPath4zip = mainPath4zip+File.separator+"java"+File.separator+packagePath+File.separator+"service"+File.separator+"impl";
        File serviceImplFile = new File(serviceImplPath+File.separator+className+"BizServiceImpl.java");
        File serviceImplBaseFile = new File(serviceImplPath+File.separator+"base"+File.separator+className+"ServiceImpl.java");
        //service.intf
        String serviceIntfPath = mainPath+File.separator+"java"+File.separator+packagePath+File.separator+"service"+File.separator+"intf";
        String serviceIntfPath4zip = mainPath4zip+File.separator+"java"+File.separator+packagePath+File.separator+"service"+File.separator+"intf";
        File serviceIntfFile = new File(serviceIntfPath+File.separator+className+"BizService.java");
        File serviceIntfBaseFile = new File(serviceIntfPath+File.separator+"base"+File.separator+className+"Service.java");
        //mapperXml
        String mapperXmlPath = mainPath+File.separator+"resources"+File.separator+"mapper";
        String mapperXmlPath4zip = mainPath4zip+File.separator+"resources"+File.separator+"mapper";
        File mapperXmlFile = new File(mapperXmlPath+File.separator+className+"BizMapper.xml");
        File mapperXmlBaseFile = new File(mapperXmlPath+File.separator+"base"+File.separator+className+"Mapper.xml");
        //dozer
        String dozerPath = mainPath+File.separator+"resources"+File.separator+"dozer";
        String dozerPath4zip = mainPath4zip+File.separator+"resources"+File.separator+"dozer";
        File dozerFile = new File(dozerPath+File.separator+className+".xml");

        // views 文件夹
        String viewPath = viewProjPath+File.separator+"src"+File.separator+"views"+File.separator+"coding"+File.separator+moduleName+File.separator+classNameFirstWordLower;
        String viewPath4zip = "easyjava"+File.separator+projectNameView+File.separator+"src"+File.separator+"views"+File.separator+"coding"+File.separator+moduleName+File.separator+classNameFirstWordLower;
        File viewFilePath = new File(viewPath);

        // core tmpt file
        String tmptPath = javaProjPath+File.separator+"core"+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"tmptFile"+File.separator+tableName;
        String tmptPath4zip = "easyjava"+File.separator+projectNameJava+File.separator+"core"+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"tmptFile"+File.separator+tableName;
        File tmptFilePath = new File(tmptPath);
        // 找最新的文件
        File[] listFiles = tmptFilePath.listFiles();
        File tmptFile = null;
        long modifiedTime = 0;
        for (File file : listFiles) {
            if (file.lastModified()>modifiedTime) {
                modifiedTime = file.lastModified();
                tmptFile = file;
            }
        }

        Map[] srcfileMap={
                getFileMap(beanPath4zip, beanFile),
                getFileMap(beanPath4zip+File.separator+"base", beanBaseFile),
                getFileMap(dtoPath4zip, dtoFile),
                getFileMap(dtoPath4zip+File.separator+"base", dtoBaseFile),
                getFileMap(mapperPath4zip, mapperFile),
                getFileMap(mapperPath4zip+File.separator+"base", mapperBaseFile),
                getFileMap(controllerPath4zip, controllerFile),
                getFileMap(controllerPath4zip+File.separator+"base", controllerBaseFile),
                getFileMap(serviceImplPath4zip, serviceImplFile),
                getFileMap(serviceImplPath4zip+File.separator+"base", serviceImplBaseFile),
                getFileMap(serviceIntfPath4zip, serviceIntfFile),
                getFileMap(serviceIntfPath4zip+File.separator+"base", serviceIntfBaseFile),
                getFileMap(mapperXmlPath4zip, mapperXmlFile),
                getFileMap(mapperXmlPath4zip+File.separator+"base", mapperXmlBaseFile),
                getFileMap(dozerPath4zip, dozerFile),
                getFileMap(viewPath4zip, viewFilePath), // views 文件夹
                getFileMap(tmptPath4zip, tmptFile), // tmpt file
        };
        //压缩后的文件
        //File zipfile=new File(File.separator+"Users"+File.separator+"wxy2020"+File.separator+"workspace"+File.separator+"easyjava.zip");
        //ZipUtils.zipFilesContainPath(srcfileMap, zipfile);

        response.setContentType("APPLICATION/OCTET-STREAM");//返回格式为流
        // response.setContentType("application/zip");//返回格式为流
        response.setHeader("Content-Disposition", "attachment; filename=easyjava.zip");

        ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
        ZipUtils.zipFilesContainPath(srcfileMap, out);
        out.flush();
        out.close();

        return null;
    }

    private Map getFileMap(String path, File file) {
        Map map = new HashMap();
        map.put("path", path);
        map.put("file", file);
        return map;
    }


    @PreAuthorize("hasAuthority('tmpt:query')")
    @ApiOperation("分页查询列表（适合单表查询）")
    @GetMapping(value = "/page")
    @ResponseBody
    public Result page(@ModelAttribute TmptTableBizDto tmptTableBizDto){
        return super.page(tmptTableBizDto, null);
    }


    @PreAuthorize("hasAuthority('tmpt:query')")
    @ApiOperation("以ID作为父节点，查询子树")
    @GetMapping(value = "/tree")
    @ResponseBody
    public Result tree (Long id) {
        return super.tree(id);
    }

    @PreAuthorize("hasAuthority('tmpt:query')")
    @ApiOperation("自定义sql分页查询（mapper.xml, 适合多表查询）")
    @GetMapping(value = "/myPage")
    @ResponseBody
    public Result myPage(@ModelAttribute TmptTableBizDto tmptTableBizDto){
        return super.myPage(tmptTableBizDto, null);
    }


    @PreAuthorize("hasAuthority('tmpt:query')")
    @ApiOperation("查询所有")
    @GetMapping(value = "/selectBy")
    @ResponseBody
    public Result selectBy(@ModelAttribute TmptTableBizDto tmptTableBizDto){
        return super.selectBy(tmptTableBizDto, null);
    }


    @PreAuthorize("hasAuthority('tmpt:query')")
    @ApiOperation("selectById")
    @GetMapping(value = "/selectById")
    @ResponseBody
    public Result selectById(Long id){
        return super.selectById(id);
    }


    @PreAuthorize("hasAuthority('tmpt:query')")
    @ApiOperation("selectBatchIds")
    @GetMapping(value = "/selectBatchIds")
    @ResponseBody
    protected Result selectBatchIds(String idListStr){
        System.out.println(idListStr);
        String[] split = idListStr.split(",");
        List<Integer> idList = new ArrayList<>();
        for(int i=0;i<split.length;i++){
            String s = split[i];
            int i1 = Integer.parseInt(s);
            idList.add(i1);
        }

        //调用服务
        return tmptTableBizService.selectBatchIds(idList);
    }


    @PreAuthorize("hasAuthority('tmpt:add-edit')")
    @ApiOperation("插入对象")
    @PostMapping(value = "/insertBankup")
    @ResponseBody
    public Result insertBankup(@RequestBody Map<String,String> fileMap){
        String fileListStr = fileMap.get("fileListStr");
        List<TmptTableBiz> tmptTableBizs = JSON.parseArray(fileListStr, TmptTableBiz.class);
        return tmptTableBizService.insertBankup(tmptTableBizs);
    }


    @PreAuthorize("hasAuthority('tmpt:query')")
    @ApiOperation("SQL动态多选项, spring动态调用")
    @GetMapping(value = "/select4column")
    @ResponseBody
    public Result select4column(String columnName){
        return super.select4column(columnName);
    }

    @PreAuthorize("hasAuthority('tmpt:add-edit')")
    @ApiOperation("新增对象")
    @PostMapping(value = "/create")
    @ResponseBody
    public Result create(@RequestBody TmptTableBizDto tmptTableBizDto,
                    String _userId, String _userName, String _companyId){
        return super.create(tmptTableBizDto, _userId, _userName, _companyId);
    }


    @PreAuthorize("hasAuthority('tmpt:add-edit')")
    @ApiOperation("编辑对象")
    @PostMapping(value = "/update")
    @ResponseBody
    public Result update(@RequestBody TmptTableBizDto tmptTableBizDto,
                        String _userId, String _userName){
        return super.update(tmptTableBizDto, _userId, _userName);
    }


    @PreAuthorize("hasAuthority('tmpt:add-edit')")
    @ApiOperation("逻辑删除对象，由deleteflag控制：0:有效，1:已删除。")
    @PostMapping(value = "/delete")
    @ResponseBody
    public Result delete(Long id, String _userId, String _userName){
        return super.delete(id, _userId, _userName);
    }


    @PreAuthorize("hasAuthority('tmptTable:deletePhysical')")
    @ApiOperation("物理删除对象，默认注释了核心调用方法，请按需启用")
    @PostMapping(value = "/deletePhysical")
    @ResponseBody
    public Result deletePhysical(Long id){
        return super.deletePhysical(id);
    }

}
